package com.bird.user.adapter.database

import com.bird.component.database.model.richEntity
import com.bird.user.adapter.database.dataobj.UserDO
import com.bird.user.adapter.database.dataobj.UserRoleDO
import com.bird.user.domain.vo.Nickname
import com.bird.user.domain.vo.Phone
import com.bird.user.domain.UserEntity
import com.bird.user.domain.vo.UserPassword

/**
 * 用户实体专数据库对象转换器
 */
fun UserEntity.toUserDO(): UserDO {
    return UserDO(
        username = this.username,
        phone = this.phone?.phone,
        password = this.password.password,
        nickname = this.nickname?.nickname,
        salt = this.salt
    ).also { it.richBase(this)}
}

/**
 * 数据库对象转用户实体
 */
fun UserDO.toUserEntity(): UserEntity {
    return UserEntity(
        username = this.username,
        phone = this.phone?.let { Phone(it) },
        password = UserPassword(password),
        nickname = this.nickname?.let { Nickname(it) },
        salt = this.salt
    ).also { it.richEntity(this) }
}

fun toUserRoles(userId: Long, roleIds: List<Long>): List<UserRoleDO> {
    if (roleIds.isEmpty()) {
        return emptyList()
    }
    return roleIds.map { roleId ->
        UserRoleDO(
            userId = userId,
            roleId = roleId
        )
    }

}